package com.example.kt_common.base

import android.util.Log
import com.alibaba.android.arouter.launcher.ARouter
import com.example.kt_common.network.BaseResp
import com.example.kt_common.network.RespStateData
import com.example.kt_common.network.RetrofitManager
import com.example.kt_common.util.Constants
import com.example.kt_common.util.ToastUtil
import retrofit2.HttpException
import java.net.ConnectException
import java.net.UnknownHostException

/**
 * Created by 小陈 on 2025/3/23.
 * Time: 11:46.
 */
open class BaseRepository {
    val TAG: String = this.javaClass.simpleName
    suspend fun <T> dealResp(
        block: suspend () -> BaseResp<T>, liveData: RespStateData<T>,
    ) {
        Log.d(TAG, "br1")
        var result = BaseResp<T>()
        result.responseState = BaseResp.ResponseState.REQUEST_START
        liveData.value = result
        try {
            Log.d(TAG, "br2")
            result = block.invoke()
            Log.d(TAG, "br3")
//            Log.d("BaseRepository", result.errorCode.toString() + "/" + result.errorMsg)
            Log.d("BaseRepository：", result.code.toString() + "/" + result.msg)
//            when (result.errorCode) {
            when (result.code) {
                Constants.HTTP_SUCCESS -> {
                    result.responseState = BaseResp.ResponseState.REQUEST_SUCCESS
                }

                Constants.HTTP_AUTH_INVALID -> {
                    result.responseState = BaseResp.ResponseState.REQUEST_FAILED
                    ToastUtil.showMsg("请先登录")
                    ARouter.getInstance().build(Constants.PATH_LOGIN).navigation()
                }

                else -> {
                    result.responseState = BaseResp.ResponseState.REQUEST_FAILED
//                    ToastUtil.showMsg("code:" + result.errorCode.toString() + " / msg:" + result.errorMsg)
                    ToastUtil.showMsg("code:" + result.code.toString() + " / msg:" + result.msg)

                }
            }

        } catch (e: Exception) {
            when (e) {
                is UnknownHostException,
                is HttpException,
                is ConnectException,
                -> {
                    //网络error
                    ToastUtil.showMsg("网络错误！")
                }
                else -> {
                    //网络error
                    ToastUtil.showMsg("未知错误！")
                    Log.d(TAG, "未知错误！${e.message}")
                }
            }
            result.responseState = BaseResp.ResponseState.REQUEST_ERROR
        }finally {
            Log.d("TestSus", "br4")
            liveData.value = result
        }
    }
}